<template>
  <view class="pc-index-bg">
    <RemindWebSocket />
    <view class="layout-container">
      <SideBar @tabChange="handleTabChange" />

      <!-- 主内容区 -->
      <view class="main-content">
        <!-- 头部标题 -->
        <view class="main-header">
          <text class="main-title">首页</text>
        </view>
        <div class="main-divider"></div>
        <!-- 主体布局 -->
        <view class="main-body main-flex">
          <!-- 左侧操作面板 -->
          <view class="left-panel">
            <button class="create-role-btn" @click="goCreateRole">
              <uni-icons type="plusempty" size="25" color="#fff" padding-right="10px" />
              创建新角色
            </button>
            <button v-if="roles.length > 0" class="edit-role-btn" @click="goEditRole">
              <uni-icons type="compose" size="25" color="#1976ed" padding-right="10px" />
              修改角色信息
            </button>
            <!-- 手机端 - 角色列表（有角色时渲染） -->
            <view class="role-list-mobile" v-if="roles.length > 0">
              <view v-for="role in roles" :key="role.id || role.relativeId || role.rid" class="role-card">
                <image class="role-avatar" :src="avatarSrc(role)" />
                <text class="role-name">{{ role.name }}</text>
                <text class="role-desc">({{ role.relationship || role.desc || "-" }})</text>
                <div class="call-buttons">
                  <div class="call-btn-wrap">
                    <span class="call-label">静态</span>
                    <button class="call-btn small" @click="goCall(role, 'audio')">
                      <uni-icons type="phone-filled" size="30" color="#fff" />
                    </button>
                  </div>
                  <div class="call-btn-wrap">
                    <span class="call-label">动态</span>
                    <button class="call-btn small video-btn" @click="goCall(role, 'video')">
                      <uni-icons type="videocam-filled" size="30" color="#fff" />
                    </button>
                  </div>
                </div>
              </view>
            </view>
            <view v-else class="empty-tip-mobile">
              暂无可选角色，点击按钮创建
            </view>
          </view>
          <!-- 右侧角色展示区 -->
          <view class="right-panel">
            <view v-if="loading" class="loading-tip">加载中…</view>
            <view v-else-if="roles.length === 0" class="empty-tip">
              暂无可选角色，点击按钮创建
            </view>
            <!-- 角色列表（有角色时渲染） -->
            <view v-else class="role-list">
              <view v-for="role in roles" :key="role.id || role.relativeId || role.rid" class="role-card">
                <image class="role-avatar" :src="avatarSrc(role)" />
                <text class="role-name">{{ role.name }}</text>
                <text class="role-desc">({{ role.relationship || role.desc || "-" }})</text>
                <div class="call-buttons">
                  <div class="call-btn-wrap">
                    <span class="call-label">静态</span>
                    <button class="call-btn small" @click="goCall(role, 'audio')">
                      <uni-icons type="phone-filled" size="30" color="#fff" />
                    </button>
                  </div>
                  <div class="call-btn-wrap">
                    <span class="call-label">动态</span>
                    <button class="call-btn small video-btn" @click="goCall(role, 'video')">
                      <uni-icons type="videocam-filled" size="30" color="#fff" />
                    </button>
                  </div>
                </div>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 点击页面其他区域关闭菜单 -->
    <view v-if="showSettingMenu" class="menu-mask" @click="showSettingMenu = false"></view>
    
    <!-- 视频模式选择对话框 -->
    <view v-if="showVideoModeDialog" class="modal-overlay" @click="showVideoModeDialog = false">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">选择视频渲染方式</text>
          <view class="modal-close" @click="showVideoModeDialog = false">✕</view>
        </view>
        <view class="modal-body">
          <button class="mode-btn" @click="selectVideoMode('trulience')">
            <view class="mode-icon">🎭</view>
            <view class="mode-info">
              <text class="mode-name">Trulience 数字人</text>
              <text class="mode-desc">外接SDK，高质量渲染</text>
            </view>
          </button>
          <button class="mode-btn" @click="selectVideoMode('img')">
            <view class="mode-icon">🖼️</view>
            <view class="mode-info">
              <text class="mode-name">图片帧模式</text>
              <text class="mode-desc">逐帧传输，兼容性好</text>
            </view>
          </button>
          <button class="mode-btn" @click="selectVideoMode('video')">
            <view class="mode-icon">🎬</view>
            <view class="mode-info">
              <text class="mode-name">视频流模式</text>
              <text class="mode-desc">流畅连贯，更自然</text>
            </view>
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onActivated, computed } from "vue";
import { go } from "@/utils/nav.js";
import SideBar from "/pages/pc/sideBar.vue";
import RemindWebSocket from "@/components/RemindWebSocket.vue";
import { useUserStore } from "@/store/modules/user";
import { useRelativeStore } from "@/store/modules/relative";
import { getUserProfile } from "@/api/pc/elderly";
const userStore = useUserStore();
const relativeStore = useRelativeStore();

const currentTab = ref("home");
const showSettingMenu = ref(false);
const showVideoModeDialog = ref(false); // 控制视频模式选择对话框
const selectedRole = ref(null); // 存储当前选择的角色

const roles = computed(() => relativeStore.processedList || []);
const loading = computed(() => relativeStore.loading);
const avatarLoading = computed(() => relativeStore.avatarLoading);
// 用于头像缓存破除的时间戳，每次刷新后更新此值
const avatarTick = ref(0);

// 生成头像地址，附带缓存破除参数（data URL 不追加）
const avatarSrc = (role) => {
  const base = role?.avatarUrl || "/static/images/p1.png";
  if (typeof base === "string" && base.startsWith("data:")) return base;
  const sep = base && base.includes && base.includes("?") ? "&" : "?";
  return `${base}${sep}_v=${avatarTick.value}`;
};

const goCreateRole = () => {
  go("/pages/pc/role-create?mode=create");
};

const goEditRole = () => {
  go("/pages/pc/role-edit");
};

const goCall = (role, callType = "audio") => {
  // 如果是视频模式，显示选择对话框
  if (callType === 'video') {
    selectedRole.value = role;
    showVideoModeDialog.value = true;
    return;
  }
  
  // 语音模式直接跳转
  navigateToChat(role, callType, '/pages/pc/aiChat_audio');
};

// 选择视频模式后的处理
const selectVideoMode = (videoMode) => {
  showVideoModeDialog.value = false;
  
  const role = selectedRole.value;
  if (!role) return;
  
  // 根据选择的视频模式跳转到不同页面
  // trulience = Trulience 数字人
  // img = 图片帧模式
  // video = 视频流模式
  let targetPage;
  if (videoMode === 'trulience') {
    targetPage = '/pages/pc/aiChat_trulience';
  } else if (videoMode === 'img') {
    targetPage = '/pages/pc/aiChat_img';
  } else {
    targetPage = '/pages/pc/aiChat_video';
  }
  
  navigateToChat(role, 'video', targetPage, videoMode);
  selectedRole.value = null;
};

// 统一的导航函数
const navigateToChat = (role, callType, targetPage, videoMode = null) => {
  const rid = role?.id ?? role?.relativeId ?? role?.rid;
  if (rid) {
    relativeStore.setCurrentRelativeId(rid);
  }

  // 获取角色头像（使用预计算的avatarUrl）
  const avatar = role.avatarUrl || "/static/images/p1.png";

  // 兜底写入通话类型，避免路由参数在某些端不生效
  try {
    sessionStorage.setItem("callType", callType);
    if (videoMode) {
      sessionStorage.setItem("videoMode", videoMode);
    }
  } catch (e) { }

  // 将完整的role数据通过query参数传递
  const queryParams = {
    avatar: avatar,
    roleName: role?.name || "亲属",
    roleRelationship: role?.relationship || role?.desc || "家人",
    callType: callType,
    videoMode: videoMode || '',
    // 传递role的所有数据
    relativeId: role?.relativeId || role?.id || role?.rid || "",
    userId: role?.userId || "",
    gender: role?.gender || "",
    age: role?.age || "",
    birthDate: role?.birthDate || "",
    hometown: role?.hometown || "",
    educationLevel: role?.educationLevel || "",
    livecity: role?.livecity || "",
    remark: role?.remark || "",
    createBy: role?.createBy || "",
    createTime: role?.createTime || "",
    updateBy: role?.updateBy || "",
    updateTime: role?.updateTime || "",
    tempRelativeId: role?.tempRelativeId || "",
  };
  
  go(targetPage, {
    query: queryParams,
  });
};

// 头像处理已移至 relativeStore 中，使用智能缓存系统

const handleTabChange = (tab) => {
  if (tab === "remind") go("/pages/pc/remind");
  if (tab === "home") go("/pages/pc/index");
};

// 强制刷新数据
const refreshData = async () => {
  if (!userStore.id) return;
  await relativeStore.fetchHomeList(userStore.id, true); // 强制刷新
  if (roles.value.length > 0) {
    relativeStore.preloadAvatars(roles.value).catch(console.warn);
  }
  // 刷新完成后更新头像 tick，触发缓存破除
  avatarTick.value = Date.now();
};

// 清除缓存
const clearCache = () => {
  relativeStore.clearCache();
  console.log("缓存已清除");
};

onMounted(async () => {
  if (!userStore.id) {
    go("/pages/pc/login", { replace: true });
    return;
  }

  const userId = userStore.id;

  // 并行执行API调用，提升加载速度
  const promises = [
    // 用户画像检查（使用缓存，避免重复调用）
    userStore.getUserProfileCached(userId),
    // 亲属列表加载（主页需要头像，使用完整数据）
    relativeStore.fetchHomeList(userId),
  ];

  try {
    const [userProfileResponse] = await Promise.all(promises);

    // 检查用户画像是否有效
    if (
      !userProfileResponse ||
      userProfileResponse.code !== 200 ||
      !userProfileResponse.data ||
      userProfileResponse.data === null ||
      typeof userProfileResponse.data !== "object"
    ) {
      go("/pages/pc/personalInfo");
      return;
    }

    // 预加载头像（懒加载）
    if (roles.value.length > 0) {
      // 异步预加载，不阻塞页面渲染
      relativeStore.preloadAvatars(roles.value).catch(console.warn);
    }
  } catch (error) {
    console.log("系统初始化完成");
  }
});

// 页面从其它路由返回时，触发刷新以更新头像
onActivated(() => {
  refreshData();
});
</script>

<style scoped>
.layout-container {
  display: flex;
  min-height: 100vh;
  background-color: #1976ed;
  border-radius: 0;
  overflow: hidden;
  position: relative;
  align-items: stretch;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 24px 0 0 24px;
  padding-top: 20px;
  overflow-y: auto;
}

.main-header {
  height: 48px;
  display: flex;
  align-items: center;
  padding-left: 32px;
  background: #fff;
  font-size: 32px;
  font-weight: 600;
}

.main-divider {
  border-bottom: 1.5px solid #e6eaf0;
  margin-top: 24px;
  margin-left: 24px;
  margin-bottom: 0;
}

.main-title {
  color: #222;
}

.main-body {
  flex: 1;
  background: #f7f8fa;
  padding: 0;
}

.main-flex {
  display: flex;
  flex-direction: row;
  height: 100%;
}

.left-panel {
  width: 280px;
  min-width: 220px;
  background: #fff;
  box-shadow: 0 2px 8px #e3e7ed;
  padding: 32px 0 24px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 18px;
  justify-content: flex-start;
  height: auto;
  flex-shrink: 0;
}

.create-role-btn {
  background: #1976ed;
  color: #fff;
  font-size: 18px;
  border-radius: 8px;
  padding: 0 16px;
  height: 60px;
  display: flex;
  align-items: center;
  border: none;
  box-shadow: 0 2px 8px #e3e7ed;
  cursor: pointer;
  width: 220px;
  justify-content: center;
}

.edit-role-btn {
  background: #ecf5ff;
  color: #1976ed;
  font-size: 18px;
  border-radius: 8px;
  padding: 0 16px;
  height: 60px;
  display: flex;
  align-items: center;
  border: 1px solid #2969ff;
  box-shadow: 0 2px 8px #e3e7ed;
  cursor: pointer;
  width: 220px;
  justify-content: center;
  margin-top: auto;
}

.edit-role-btn uni-icons {
  margin-right: 4px;
}

.right-panel {
  flex: 1;
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
  padding: 32px 0 0 60px;
  max-height: calc(100vh - 100px);
  overflow-y: auto;
}

.role-list {
  display: flex;
  flex-wrap: wrap;
  gap: 32px 32px;
}

.main-body.main-flex {
  flex: 1 1 auto;
  min-height: 0;
  height: auto;
}

.empty-tip {
  color: #888;
  font-size: 15px;
  margin-left: 32px;
}

.empty-tip-mobile {
  color: #888;
  font-size: 15px;
  margin-top: 20px;
  width: 100%;
  text-align: center;
}

.menu-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: transparent;
  z-index: 5;
}

.role-card {
  width: 282px;
  height: 363px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 16px #e3e7ed;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 32px 0 18px 0;
  position: relative;
  margin-bottom: 0;
}

.role-avatar {
  width: 180px;
  height: 320px;
  border-radius: 50%;
  object-fit: cover;
  margin-bottom: 12px;
}

.role-name {
  height: 35px;
  font-size: 30px;
  font-weight: 500;
  color: #222;
  margin-bottom: 2px;
  text-align: center;
}

.role-desc {
  height: 35px;
  font-size: 15px;
  color: #888;
  margin-bottom: 16px;
  text-align: center;
}

.call-buttons {
  display: flex;
  gap: 12px;
  margin-top: 8px;
}

.call-btn-wrap {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
}

.call-label {
  font-size: 12px;
  color: #666;
  line-height: 1;
}

.call-btn {
  background: #19c37d;
  color: #fff;
  border: none;
  border-radius: 30px;
  width: 80px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px #e3e7ed;
  cursor: pointer;
  transition: all 0.2s ease;
}

.call-btn:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px #e3e7ed;
}

.call-btn.small {
  width: 80px;
  height: 45px;
}

.video-btn {
  background: #00adb9 !important;
}

.video-btn:hover {
  background: #00adb9 !important;
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 173, 185, 0.3);
}

.loading-tip {
  color: #888;
  font-size: 14px;
  margin-left: 32px;
}

/* 头像加载状态 */
.avatar-loading {
  opacity: 0.6;
  transition: opacity 0.3s ease;
}

.role-avatar {
  transition: all 0.3s ease;
}

.role-avatar:hover {
  transform: scale(1.02);
}

/* ===== 视频模式选择对话框 ===== */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.2s ease;
}

.modal-content {
  background: #fff;
  border-radius: 16px;
  width: 90%;
  max-width: 480px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  animation: slideUp 0.3s ease;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-title {
  font-size: 18px;
  font-weight: 600;
  color: #222;
}

.modal-close {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  border-radius: 50%;
  transition: all 0.2s ease;
}

.modal-close:hover {
  background: #f5f5f5;
  color: #666;
}

.modal-body {
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.mode-btn {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: #f8f9fa;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.mode-btn:hover {
  background: #f0f7ff;
  border-color: #1976ed;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(25, 118, 237, 0.15);
}

.mode-icon {
  font-size: 48px;
  line-height: 1;
}

.mode-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
  text-align: left;
}

.mode-name {
  font-size: 16px;
  font-weight: 600;
  color: #222;
}

.mode-desc {
  font-size: 13px;
  color: #666;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 手机适配 - 对话框样式 */
@media screen and (max-width: 768px) {
  .modal-content {
    width: 95%;
    max-width: 380px;
  }
  
  .modal-header {
    padding: 16px 20px;
  }
  
  .modal-title {
    font-size: 16px;
  }
  
  .modal-body {
    padding: 16px 20px;
    gap: 12px;
  }
  
  .mode-btn {
    padding: 16px;
  }
  
  .mode-icon {
    font-size: 40px;
  }
  
  .mode-name {
    font-size: 15px;
  }
  
  .mode-desc {
    font-size: 12px;
  }
}

/* ===== 手机适配样式 ===== */
@media screen and (min-width: 300px) and (max-width: 768px) {
  .left-panel {
    width: 100%;
    min-width: 220px;
    box-shadow: 0 2px 8px #e3e7ed;
    padding: 32px 0 24px 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 18px;
    justify-content: flex-start;
    height: auto;
    flex-shrink: 0;
  }

  .role-list-mobile {
    display: flex;
    flex-wrap: wrap;
    gap: 32px 32px;
    justify-content: center;
    overflow: scroll;
    min-height: 50vh;
    height: 90vh;
    /* 备用值 */
    height: calc(100vh - 350px);
  }

  .edit-role-btn {
    background: #ecf5ff;
    color: #1976ed;
    font-size: 18px;
    border-radius: 8px;
    padding: 0 16px;
    height: 60px;
    display: flex;
    align-items: center;
    border: 1px solid #2969ff;
    box-shadow: 0 2px 8px #e3e7ed;
    cursor: pointer;
    width: 220px;
    justify-content: center;
    margin-top: 0;
  }
}

@media screen and (min-width: 768px) {

  /* .right-panel {
    display: none;
  } */
  .role-list-mobile {
    display: none;
  }

  .empty-tip-mobile {
    display: none;
  }
}
</style>
